"""
分档明细API路由
"""
from flask import Blueprint, jsonify
from app.models.ip_config import IpConfig
from flask_jwt_extended import jwt_required


bp = Blueprint('segment_details', __name__, url_prefix='/api/segment-details')


@bp.route('/', methods=['GET'])
@jwt_required()
def get_segment_details():
    """获取分档明细数据"""
    try:
        # 获取所有IP配置（包括未启用的）
        ip_configs = IpConfig.query.all()
        
        # 如果没有数据，返回空列表
        if not ip_configs:
            return jsonify({
                'success': True,
                'data': [],
                'message': '暂无分档明细数据'
            })
        
        # 按车间分组数据
        workshop_data = {}
        
        for config in ip_configs:
            workshop = config.workshop
            if workshop not in workshop_data:
                workshop_data[workshop] = {
                    'workshop': workshop,
                    'segments': [],
                    'last_updated': None
                }
            
            # 添加分档信息
            segment_info = {
                'id': config.id,
                'line': config.line,
                'current_segment': config.current_segment,
                'ip': config.ip,
                'is_enabled': config.is_enabled,
                'updated_at': config.updated_at.strftime('%Y-%m-%d %H:%M:%S') if config.updated_at else ''
            }
            
            workshop_data[workshop]['segments'].append(segment_info)
            
            # 更新最后修改时间（取最新的）
            if config.updated_at:
                current_time_str = config.updated_at.strftime('%Y-%m-%d %H:%M:%S')
                if (workshop_data[workshop]['last_updated'] is None or 
                    config.updated_at.strftime('%Y-%m-%d %H:%M:%S') > workshop_data[workshop]['last_updated']):
                    workshop_data[workshop]['last_updated'] = current_time_str
        
        # 转换为列表格式
        result = list(workshop_data.values())
        
        return jsonify({
            'success': True,
            'data': result,
            'message': '获取分档明细成功'
        })
        
    except Exception as e:
        import traceback
        print(f"分档明细API错误: {str(e)}")
        print(traceback.format_exc())
        return jsonify({
            'success': False,
            'message': f'获取分档明细失败: {str(e)}'
        }), 500


@bp.route('/by-workshop/<workshop>', methods=['GET'])
@jwt_required()
def get_segment_details_by_workshop(workshop):
    """根据车间获取分档明细"""
    try:
        # 获取指定车间的所有IP配置（包括未启用的）
        ip_configs = IpConfig.query.filter_by(workshop=workshop).all()
        
        if not ip_configs:
            return jsonify({
                'success': False,
                'message': f'未找到车间 {workshop} 的分档数据'
            }), 404
        
        segments = []
        last_updated = None
        
        for config in ip_configs:
            segment_info = {
                'id': config.id,
                'line': config.line,
                'current_segment': config.current_segment,
                'ip': config.ip,
                'updated_at': config.updated_at.strftime('%Y-%m-%d %H:%M:%S')
            }
            segments.append(segment_info)
            
            # 更新最后修改时间
            if last_updated is None or config.updated_at > last_updated:
                last_updated = config.updated_at.strftime('%Y-%m-%d %H:%M:%S')
        
        return jsonify({
            'success': True,
            'data': {
                'workshop': workshop,
                'segments': segments,
                'last_updated': last_updated
            },
            'message': f'获取车间 {workshop} 分档明细成功'
        })
        
    except Exception as e:
        return jsonify({
            'success': False,
            'message': f'获取分档明细失败: {str(e)}'
        }), 500